import { createRouter, createWebHistory } from 'vue-router'
import LoginForm from '@/views/login_register/LoginForm.vue'
import RegisterForm from '@/views/login_register/RegisterForm.vue'
import LoginRegisterForm from '@/views/login_register/LoginRegisterForm.vue'
import Dashboard from '@/views/home_page/Dashboard.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/login_register' }, // 默认跳转到组合登录注册页
    { path: '/login', component: LoginForm }, // 登录路由
    { path: '/register', component: RegisterForm }, // 注册路由
    { path: '/login_register', component: LoginRegisterForm }, // 注册路由
    { 
      path: '/dashboard', 
      component: Dashboard,
      meta: { requiresAuth: true } // 标记需要认证的路由
    },
    { path: '/Dashboard', component: Dashboard },//主页
  ],
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户是否已登录
    const userId = localStorage.getItem('userid');
    const token = localStorage.getItem('token');
    
    if (!userId || !token) {
      // 如果未登录，重定向到登录页
      next({ path: '/login_register' });
    } else {
      // 已登录，继续访问
      next();
    }
  } else {
    // 不需要认证的路由，直接访问
    next();
  }
});

export default router
